package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.util.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private CartService cartService;

    @Reference
    private SkuService skuService;


    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IdWorker idWorker;
    /**
     * 返回全部记录
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param order
     */
    public void add(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 修改
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 新增订单
     * @param order
     * @return
     */
    @Override
    @Transactional
    public Map submitOrder(String name,Order order) {
        // tb_order 新增一条记录     tb_order_item 新增多条记录    修改库存、销量 tb_sku  从购物车中删除已经购买过的商品清单
        //0. 获取当前用户准备购买哪些商品
        // A  2  100   1000
        // B   1   100  1000
        // C   1    1000  1000
        // 3000
        // 1000  -100
        // 1300-300   2700
        //
        List<OrderItem> buyOrderItems = cartService.getBuyOrderItems(name);
        //1. 判断库存是否够
        for(OrderItem orderItem : buyOrderItems){
            String skuId = orderItem.getSkuId();
            Sku sku = skuService.findById(skuId);
            Integer kuCun = sku.getNum();//库存量
            if(orderItem.getNum()>kuCun){//库存不够
                return null;// 下订单失败
            }
        }

        //2. 修改库存、销量
        // update tb_sku set num = num -xxx , sale_num = sale_num + xxx where id = xxx  减库存
        // update tb_sku set num = num - -xxx , sale_num = sale_num +- xxx where id = xxx
       if (!skuService.updateKuCun(buyOrderItems)){
           return null;//库存扣减失败，停止下订单
       }
        //3. 新增订单，订单详情的记录
        /*
                新增时：
                    数据： 1. 用户填写的   2.系统设置的默认值    3. 特殊的业务需求
         */
        //新增一条订单  Order
        //设置订单的购买的数量
        try {
            int totalNum = 0;
            int totalMoney = 0;
            for(OrderItem orderItem : buyOrderItems){
                totalNum+= orderItem.getNum();
                totalMoney+= orderItem.getNum() * orderItem.getPrice();
            }
            order.setTotalNum(totalNum);
            //设置订单金额总计
            order.setTotalMoney(totalMoney);
            //设置订单的优惠金额
            Integer preferentialMoney = cartService.getPreferentialMoney(name);
            order.setPreMoney(preferentialMoney);
            //订单创建时间
            Date now = new Date();
            order.setCreateTime(now);
            //用户名称
            order.setUsername(name);
            //订单来源  1
            order.setSourceType("1");
            //订单状态 0待付款
            order.setOrderStatus("0");
            //支付状态 0未支付
            order.setPayStatus("0");
            // 发货状态  0未发货
            order.setConsignStatus("0");
            //删除的状态  0：未删除
            order.setIsDelete("0");

            //设置应该金额
            order.setPayMoney(order.getTotalMoney()-order.getPreMoney());

            //订单号  订单ID
            order.setId(idWorker.nextId()+"");
            orderMapper.insert(order);

            //新增订单项的信息
            for(OrderItem orderItem : buyOrderItems){
              orderItem.setId(idWorker.nextId()+"");//自己的ID
              orderItem.setOrderId(order.getId());//订单号的ID
              orderItem.setIsReturn("0");
                int rate = order.getPreMoney() / order.getTotalMoney();
                orderItem.setPayMoney(orderItem.getNum()*orderItem.getPrice()*rate);
                int rows = orderItemMapper.insert(orderItem);
                System.out.println(rows);

            }
            int i = 2/0;
        } catch (Exception e) {
            //捕获到异常，下订单失败
            rabbitTemplate.convertAndSend("","queue.stockback",JSON.toJSONString(buyOrderItems));
            throw  new RuntimeException("下订单失败了！！");
        }

        //4. 购物车删除已经购买过的商品清单 判断库存是否够
        cartService.deleteCheckedCartItems(name);
        HashMap  map = new HashMap<>();
        map.put("orderId",order.getId());//订单号
        map.put("payMoney",order.getPayMoney());//实付金额
        return map;
    }
    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 订单id
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if(searchMap.get("payType")!=null && !"".equals(searchMap.get("payType"))){
                criteria.andLike("payType","%"+searchMap.get("payType")+"%");
            }
            // 物流名称
            if(searchMap.get("shippingName")!=null && !"".equals(searchMap.get("shippingName"))){
                criteria.andLike("shippingName","%"+searchMap.get("shippingName")+"%");
            }
            // 物流单号
            if(searchMap.get("shippingCode")!=null && !"".equals(searchMap.get("shippingCode"))){
                criteria.andLike("shippingCode","%"+searchMap.get("shippingCode")+"%");
            }
            // 用户名称
            if(searchMap.get("username")!=null && !"".equals(searchMap.get("username"))){
                criteria.andLike("username","%"+searchMap.get("username")+"%");
            }
            // 买家留言
            if(searchMap.get("buyerMessage")!=null && !"".equals(searchMap.get("buyerMessage"))){
                criteria.andLike("buyerMessage","%"+searchMap.get("buyerMessage")+"%");
            }
            // 是否评价
            if(searchMap.get("buyerRate")!=null && !"".equals(searchMap.get("buyerRate"))){
                criteria.andLike("buyerRate","%"+searchMap.get("buyerRate")+"%");
            }
            // 收货人
            if(searchMap.get("receiverContact")!=null && !"".equals(searchMap.get("receiverContact"))){
                criteria.andLike("receiverContact","%"+searchMap.get("receiverContact")+"%");
            }
            // 收货人手机
            if(searchMap.get("receiverMobile")!=null && !"".equals(searchMap.get("receiverMobile"))){
                criteria.andLike("receiverMobile","%"+searchMap.get("receiverMobile")+"%");
            }
            // 收货人地址
            if(searchMap.get("receiverAddress")!=null && !"".equals(searchMap.get("receiverAddress"))){
                criteria.andLike("receiverAddress","%"+searchMap.get("receiverAddress")+"%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(searchMap.get("sourceType")!=null && !"".equals(searchMap.get("sourceType"))){
                criteria.andLike("sourceType","%"+searchMap.get("sourceType")+"%");
            }
            // 交易流水号
            if(searchMap.get("transactionId")!=null && !"".equals(searchMap.get("transactionId"))){
                criteria.andLike("transactionId","%"+searchMap.get("transactionId")+"%");
            }
            // 订单状态
            if(searchMap.get("orderStatus")!=null && !"".equals(searchMap.get("orderStatus"))){
                criteria.andLike("orderStatus","%"+searchMap.get("orderStatus")+"%");
            }
            // 支付状态
            if(searchMap.get("payStatus")!=null && !"".equals(searchMap.get("payStatus"))){
                criteria.andLike("payStatus","%"+searchMap.get("payStatus")+"%");
            }
            // 发货状态
            if(searchMap.get("consignStatus")!=null && !"".equals(searchMap.get("consignStatus"))){
                criteria.andLike("consignStatus","%"+searchMap.get("consignStatus")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }

            // 数量合计
            if(searchMap.get("totalNum")!=null ){
                criteria.andEqualTo("totalNum",searchMap.get("totalNum"));
            }
            // 金额合计
            if(searchMap.get("totalMoney")!=null ){
                criteria.andEqualTo("totalMoney",searchMap.get("totalMoney"));
            }
            // 优惠金额
            if(searchMap.get("preMoney")!=null ){
                criteria.andEqualTo("preMoney",searchMap.get("preMoney"));
            }
            // 邮费
            if(searchMap.get("postFee")!=null ){
                criteria.andEqualTo("postFee",searchMap.get("postFee"));
            }
            // 实付金额
            if(searchMap.get("payMoney")!=null ){
                criteria.andEqualTo("payMoney",searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
